package com.tencent.qcloud.timchat.utils;

import android.util.Log;

import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.message.TIMConversationExt;
import com.tencent.imsdk.ext.message.TIMManagerExt;
import com.wbao.dianniu.db.TencentUserBean;
import com.wbao.dianniu.db.TencentUserHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 会话界面逻辑
 */
public class ConversationPresenter implements Observer {

    private static final String TAG = "ConversationPresenter";
    private ConversationView view;

    public ConversationPresenter(ConversationView view) {
        //注册消息监听
        MessageEvent.getInstance().addObserver(this);
        //注册刷新监听
        RefreshEvent.getInstance().addObserver(this);
        //注册好友关系链监听
        FriendshipEvent.getInstance().addObserver(this);
        this.view = view;
    }

    @Override
    public void update(Observable observable, Object data) {
        if (observable instanceof MessageEvent) {
            if (data instanceof TIMMessage) {
//                Log.e(TAG,"update....TIMMessage");
                TIMMessage msg = (TIMMessage) data;
                view.updateMessage(msg);
            }
        } else if (observable instanceof FriendshipEvent) {
//            Log.e(TAG,"update....FriendshipEvent");
            FriendshipEvent.NotifyCmd cmd = (FriendshipEvent.NotifyCmd) data;
            switch (cmd.type) {
                case ADD_REQ:
                case READ_MSG:
                case ADD:
                    view.updateFriendshipMessage();
                    break;
            }
        } else if (observable instanceof RefreshEvent) {
//            Log.e(TAG,"update....RefreshEvent");
            getConversation();
            view.refresh();
        }
    }


    public void getConversation() {
        List<TIMConversation> list = TIMManagerExt.getInstance().getConversationList();
        List<TIMConversation> result = new ArrayList<>();
        List<String> users = new ArrayList<>();
        for (TIMConversation conversation : list) {
            if (conversation.getType() == TIMConversationType.System) continue;
            result.add(conversation);
            users.add(conversation.getPeer());
            TIMConversationExt conversationExt = new TIMConversationExt(conversation);
            conversationExt.getMessage(1, null, new TIMValueCallBack<List<TIMMessage>>() {
                @Override
                public void onError(int i, String s) {
//                    Log.e(TAG, "get message error" + s);
                }

                @Override
                public void onSuccess(List<TIMMessage> timMessages) {
                    if (timMessages.size() > 0) {
                        view.updateMessage((TIMMessage) timMessages.get(0));
                    }

                }
            });

        }
        /*for (int i = 0; i < users.size(); i++) {
            Log.e("TAG", "用户头像数据请求参数： " + i + "=" + users.get(i));
        }*/
//        reqUserProfile(users);
        view.initView(result);
    }


    /**
     * 当没有用户头像数据时，请求用户头像数据...
     *
     * @param users
     */
    public void reqUserProfile(List<String> users) {
        // 请求头像数据
        TIMFriendshipManager.getInstance().getUsersProfile(users, new TIMValueCallBack<List<TIMUserProfile>>() {
            @Override
            public void onError(int i, String s) {
                Log.e(TAG, "getUsersProfile failed: " + i + " desc:" + s);
            }

            @Override
            public void onSuccess(List<TIMUserProfile> timUserProfiles) {
                if (null != timUserProfiles && timUserProfiles.size() > 0) {
                    // 更新到缓存...
                    for (int i = 0; i < timUserProfiles.size(); i++) {
//                        Log.e(TAG, i + " 收到头像数据 并更新... " + timUserProfiles.get(i).getNickName() + " faceUrl:" + timUserProfiles.get(i).getFaceUrl());
                        TencentUserBean bean = new TencentUserBean();
                        bean.setIdentify(timUserProfiles.get(i).getIdentifier());
                        bean.setNiceName(timUserProfiles.get(i).getNickName());
                        bean.setFaceUrl(timUserProfiles.get(i).getFaceUrl());
                        TencentUserHelper.insertTencentUser(bean);
                    }
                    view.updateHeadUrlAndName(timUserProfiles);
                }
            }
        });
    }

    /**
     * 删除会话
     *
     * @param type 会话类型
     * @param id   会话对象id
     */
    public boolean delConversation(TIMConversationType type, String id) {
        return TIMManagerExt.getInstance().deleteConversationAndLocalMsgs(type, id);
    }


    /**
     * 删除会话，但不删除本地缓存
     *
     * @param type
     * @param id
     * @return
     */
    public boolean delConversationNot(TIMConversationType type, String id) {
        boolean ret = TIMManagerExt.getInstance().deleteConversation(type, id);
//        Log.e(TAG,"  ret:" + ret + " type: " + type + "  id:" + id);
        if (ret) {
            view.removeConversation(id);
        }
        return ret;
    }

}
